#!/usr/bin/env python3
"""
MCP Server Debug Script
调试MCP服务器问题的脚本

Usage:
    python test/debug_mcp.py
"""

import sys
import os
import json
import subprocess
import platform
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    print("🔍 Checking Python version...")
    
    version = sys.version_info
    print(f"Python version: {version.major}.{version.minor}.{version.micro}")
    
    if version.major == 3 and version.minor >= 10:
        print("✅ Python version is compatible (>=3.10)")
        return True
    else:
        print("❌ Python version is too old. Requires Python 3.10+")
        print("Please upgrade Python or use uv to manage Python versions")
        return False

def check_uv_installation():
    """检查uv是否安装"""
    print("\n🔍 Checking uv installation...")
    
    try:
        result = subprocess.run(["uv", "--version"], capture_output=True, text=True)
        if result.returncode == 0:
            print(f"✅ uv installed: {result.stdout.strip()}")
            return True
        else:
            print("❌ uv not working properly")
            return False
    except FileNotFoundError:
        print("❌ uv not found. Please install uv first:")
        print("   Windows: winget install --id=astral-sh.uv -e")
        print("   macOS: brew install uv")
        print("   Linux: curl -LsSf https://astral.sh/uv/install.sh | sh")
        return False

def check_virtual_environment():
    """检查虚拟环境"""
    print("\n🔍 Checking virtual environment...")
    
    project_root = Path(__file__).parent.parent
    venv_path = project_root / ".venv"
    
    if venv_path.exists():
        print("✅ Virtual environment exists")
        
        # Check if Python executable exists
        if platform.system() == "Windows":
            python_exe = venv_path / "Scripts" / "python.exe"
        else:
            python_exe = venv_path / "bin" / "python"
        
        if python_exe.exists():
            print("✅ Python executable found in venv")
            
            # Check Python version in venv
            try:
                result = subprocess.run([str(python_exe), "--version"], 
                                      capture_output=True, text=True)
                print(f"✅ Venv Python version: {result.stdout.strip()}")
                return True
            except Exception as e:
                print(f"❌ Error checking venv Python: {e}")
                return False
        else:
            print("❌ Python executable not found in venv")
            return False
    else:
        print("❌ Virtual environment not found")
        print("Run: uv venv --python 3.11")
        return False

def check_dependencies():
    """检查依赖安装"""
    print("\n🔍 Checking dependencies...")
    
    project_root = Path(__file__).parent.parent
    
    try:
        result = subprocess.run(
            ["uv", "run", "python", "-c", "import fastmcp, pyside6, psutil, markdown; print('All dependencies OK')"],
            cwd=project_root,
            capture_output=True,
            text=True
        )
        
        if result.returncode == 0:
            print("✅ All dependencies installed")
            return True
        else:
            print("❌ Dependencies missing or broken")
            print(f"Error: {result.stderr}")
            print("Run: uv sync")
            return False
            
    except Exception as e:
        print(f"❌ Error checking dependencies: {e}")
        return False

def check_mcp_config():
    """检查MCP配置"""
    print("\n🔍 Checking MCP configuration...")
    
    # Common MCP config locations
    config_paths = []
    
    if platform.system() == "Windows":
        config_paths = [
            Path.home() / "AppData" / "Roaming" / "Claude" / "claude_desktop_config.json",
            Path.home() / "AppData" / "Local" / "Claude" / "claude_desktop_config.json"
        ]
    elif platform.system() == "Darwin":  # macOS
        config_paths = [
            Path.home() / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json"
        ]
    else:  # Linux
        config_paths = [
            Path.home() / ".config" / "claude" / "claude_desktop_config.json"
        ]
    
    config_found = False
    for config_path in config_paths:
        if config_path.exists():
            print(f"✅ Found MCP config: {config_path}")
            config_found = True
            
            try:
                with open(config_path, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                
                if "mcpServers" in config:
                    servers = config["mcpServers"]
                    if "interactive-feedback" in servers:
                        print("✅ interactive-feedback server configured")
                        server_config = servers["interactive-feedback"]
                        print(f"   Command: {server_config.get('command', 'Not set')}")
                        if "autoApprove" in server_config:
                            print(f"   Auto-approve: {server_config['autoApprove']}")
                    else:
                        print("❌ interactive-feedback server not found in config")
                else:
                    print("❌ No mcpServers section in config")
                    
            except Exception as e:
                print(f"❌ Error reading config: {e}")
            
            break
    
    if not config_found:
        print("❌ No MCP config file found")
        print("Expected locations:")
        for path in config_paths:
            print(f"   {path}")
    
    return config_found

def test_server_manually():
    """手动测试服务器启动"""
    print("\n🔍 Testing server startup manually...")
    
    project_root = Path(__file__).parent.parent
    
    try:
        print("Starting server with uv run...")
        result = subprocess.run(
            ["uv", "run", "server.py"],
            cwd=project_root,
            timeout=5,
            capture_output=True,
            text=True
        )
        
        print("Server output:")
        if result.stdout:
            print(f"STDOUT: {result.stdout}")
        if result.stderr:
            print(f"STDERR: {result.stderr}")
            
        if "Interactive Feedback MCP" in result.stderr:
            print("✅ Server started successfully")
            return True
        else:
            print("❌ Server startup failed")
            return False
            
    except subprocess.TimeoutExpired:
        print("✅ Server started (timeout expected for stdio mode)")
        return True
    except Exception as e:
        print(f"❌ Error testing server: {e}")
        return False

def provide_fix_suggestions():
    """提供修复建议"""
    print("\n🔧 FIX SUGGESTIONS")
    print("="*50)
    
    print("If you encounter issues, try these steps in order:")
    print()
    print("1. Fix Python version:")
    print("   uv venv --python 3.11")
    print()
    print("2. Install dependencies:")
    print("   uv sync")
    print()
    print("3. Test server manually:")
    print("   uv run server.py")
    print()
    print("4. Check MCP config file contains:")
    print('   {')
    print('     "mcpServers": {')
    print('       "interactive-feedback": {')
    print('         "command": "uv",')
    print('         "args": ["--directory", "D:/python/feedback/interactive-feedback-mcp-main", "run", "server.py"],')
    print('         "timeout": 600,')
    print('         "autoApprove": ["interactive_feedback"]')
    print('       }')
    print('     }')
    print('   }')

def main():
    """运行所有诊断检查"""
    print("🔧 MCP Server Debug Tool")
    print("="*50)
    
    checks = [
        ("Python Version", check_python_version),
        ("UV Installation", check_uv_installation), 
        ("Virtual Environment", check_virtual_environment),
        ("Dependencies", check_dependencies),
        ("MCP Configuration", check_mcp_config),
        ("Server Startup", test_server_manually),
    ]
    
    results = []
    
    for check_name, check_func in checks:
        try:
            result = check_func()
            results.append((check_name, result))
        except Exception as e:
            print(f"❌ Check failed: {e}")
            results.append((check_name, False))
    
    # Summary
    print("\n" + "="*50)
    print("DIAGNOSTIC SUMMARY")
    print("="*50)
    
    passed = 0
    for check_name, result in results:
        status = "✅ OK" if result else "❌ ISSUE"
        print(f"{check_name}: {status}")
        if result:
            passed += 1
    
    print(f"\nChecks passed: {passed}/{len(results)}")
    
    if passed < len(results):
        provide_fix_suggestions()
    else:
        print("\n🎉 All checks passed! Your MCP server should work correctly.")

if __name__ == "__main__":
    main()
